<?php
error_reporting(E_ALL ^E_NOTICE);
class Index extends Action {
	function initAction() {
        print_r($_POST);
        print_r($_GET);
        print_r($_COOKIE);
		//$userId = '11';
		//$groupId = '11';
		//$this->canAction($userId, $groupId);
		// 设定 cookie
		//setcookie("cookie[three]", "cookiethree");
		//setcookie("cookie[two]", "cookietwo");
		//setcookie("cookie[one]", "cookieone");
		//setcookie('cookie', '');
		// 刷新页面后，显示出来
		//if (isset($_COOKIE['cookie'])) {
		//    foreach ($_COOKIE['cookie'] as $name => $value) {
		//        echo "$name : $value <br />\n";
		//    }
		//}
		//setcookie('test_LoginFlag', 'acd3K0ollvGU0piJBphXoxQ8zWCy4JEiCfj1w1yACBopR+4pKrRytg');
		//setcookie('testLoginFlag', '');
		//echo "<pre>";print_r($_COOKIE);
	}
    
	public function indexAction() 
	{
		$viewObj = new account(false);
		Loader('mod::account');
		Loader('account');
		Loader('sys::cache');
		//Loader('app::cache');


		//exit('hello');
        if (!isset($_POST['submit'])) {   
            $viewObj = new View(false);
            if (!$viewObj->is_cached('start')) {
                $title = '开始';
                $viewObj->assign('title', $title);
            }
            $viewObj->display('start');     
        }else{
            $accountObj = new account();  
            //$table = '`discuz`.`cdb_threads`';
            //$table = 'account'; 
            $db = isset($_POST['db']) ?  trim($_POST['db']) : 'qsf_mvc';   
            //$table =  'qsf_filed';
            $table = isset($_POST['table']) ?  trim($_POST['table']) : 'website';  
            $filedObj = new filed();
            $filedCount = $filedObj->getCount("`db` = '{$db}' and `table` = '{$table}'");
            if ($filedCount) {
                //exit($filedCount);
                $viewObj = new View(false);
                //if (!$viewObj->is_cached('menu')) { 
                    $title = '操作';
                    $viewObj->assign('title', $title)
                            ->assign('db', $db)
                            ->assign('table', $table);
                //} 
                $viewObj->display('menu');
                exit();  
            }
            $showdescRs = $accountObj->show("DESC $db.$table");
            $showcreateRs = $accountObj->show("show create table $db.$table", true);
            //print_r($showcreateRs);
            preg_match('/CREATE\s*TABLE\s*`\w*`\s*\((.+)\)\s*(.+)/is', $showcreateRs['Create Table'], $create); 
            //$showindexRs = $accountObj->show('show index from account');
            //print_r($showindexRs);  
            //print_r($showdescRs);
            $columnsArr = array();
            foreach($showdescRs as $key => $value) {
                $columnName = $showdescRs[$key]['Field'];
                preg_match('/(\w+)\(?(\d*)\)?(\s*\w*\s*)?/is', $showdescRs[$key]['Type'], $matches);
                $columnsArr[$columnName]['field']      =  $columnName;
                $columnsArr[$columnName]['type']       =  $matches[1];   
                $columnsArr[$columnName]['length']     =  isset($matches[2]) ? trim($matches[2]) : ''; 
                $columnsArr[$columnName]['attribute']  =  isset($matches[3]) ? trim($matches[3]) : '';
                $columnsArr[$columnName]['null']       =  strtolower($showdescRs[$key]['Null']);  
                $columnsArr[$columnName]['default']    =  strtolower($showdescRs[$key]['Default']);
                $columnsArr[$columnName]['key']        =  strtolower($showdescRs[$key]['Key']);
                $columnsArr[$columnName]['extra']      =  strtolower($showdescRs[$key]['Extra']);
                preg_match('/`'.$columnName.'`.*COMMENT\s*\'(.*)\',/isU', $create[1], $comment); 
                $columnsArr[$columnName]['comment']      =  isset($comment[1]) ? trim($comment[1]) : ''; 
                unset($columnName,$key,$value);
            }
            //print_r($columnsArr);
            
            $indexArr = array();

            //print_r($create); 
              

     
            preg_match_all('/\w*\sKEY.*\(.*\)/isU', $create[1], $index);                                                                                                           

              
            //print_r($index);
            if (!empty($index[0])) {
                foreach ($index[0] as $k => $v) {
                     preg_match_all('/(.*)KEY(.*)\((.*)\)/isU', $v, $key);
                     //print_r($key);
                     $type = strtolower(trim($key[1][0]));
                     $indexName = $type == 'primary' ? trim(trim($key[3][0]), '`') : trim(trim($key[2][0]), '`');
                     $indexArr[$indexName]['indexname']  =  $indexName; 
                     $indexArr[$indexName]['type']  = $type != '' ? $type : 'mul'; 
                     $indexValue  = explode(',', $key[3][0]);
                     $indexArr[$indexName]['value'][] = count($indexValue);
                     foreach($indexValue as $key => $value) {
                        $indexArr[$indexName]['value'][] = trim(trim($value), '`');
                     }   
                }
            
            }
            $charset = '';
            $engine = '';
            //echo $create[2];
            if (!empty($create[2])) {
                preg_match('/ENGINE=(\w+)\s.*CHARSET=(\w+)\s/is', $create[2], $charset);
                //print_r($charset); 
                $engine  = isset($charset[1]) ? trim($charset[1]) : '';      
                $charset = isset($charset[2]) ? trim($charset[2]) : '';                                                              
            }
            //print_r($indexArr);
            $desc = array('db'  => $db, 'table'  => $table, 'engine' => $engine, 'charset' => $charset, 'columns' => $columnsArr, 'index' => $indexArr);
            //print_r($desc);exit();
            //echo '<hr>';
            //exit();
            $viewObj = new View(false);
            $viewObj->template_dir    = APP_PATH.'/views/'.$_GET['module'].'/';
            $viewObj->compile_dir     = APP_PATH.'/views_c/'.$_GET['module'].'/';
            $viewObj->cache_dir       = APP_PATH.'/cache/'.$_GET['module'].'/';
            $viewObj->caching = false;
            $viewObj->cache_lifetime = 0;
            if (!$viewObj->is_cached('view')) {
                $title = '模板';
                $viewObj->assign('title', $title)
                        ->assign('desc', $desc); 
            }
            $viewObj->display('view');         
        }
	}

   function filedAction() {
        if (isset($_POST['submit'])) {
            echo '<pre>';
            //print_r($_POST);
            //exit();
            unset($_POST['submit']);
            $filedsData = array();
            $filedsData['db'] = $_POST['qsf_db'];
            $filedsData['table'] = $_POST['qsf_table'];
            $filedsData['charset'] = $_POST['qsf_charset'];
            $filedsData['primaryKey'] = isset($_POST['ukey']) ? $_POST['ukey'] : (isset($_POST['ukey1']) ? $_POST['ukey1'] : '');
            unset($_POST['qsf_db'], $_POST['qsf_table'], $_POST['qsf_charset'], $_POST['ukey'], $_POST['ukey1']);
            //exit();
            //print_r($_POST);     
            $filedObj = new filed();
            foreach ($_POST as $k => $v) {
                $filedsData['enname']     = $v['enname'];
                $filedsData['cnname']     = $v['cnname'];  
                $filedsData['form']       = $v['form'];  
                $filedsData['formlength'] = (int)$v['formlength']; 
                $filedsData['list']       = isset($v['list']) ? (int)$v['list'] : 0;
                $filedsData['add']        = isset($v['add'])  ? (int)$v['add']  : 0;       
                $filedsData['need']       = isset($v['need']) ? (int)$v['need'] : 0;       
                $filedsData['edit']       = isset($v['edit']) ? (int)$v['edit'] : 0;       
                $filedsData['view']       = isset($v['view']) ? (int)$v['view'] : 0;                           
                //print_r($filedsData);exit();
                $insetId = $filedObj->insert($filedsData); 
                if ($insetId > 0) {
                    //echo "插入ID为:{$insetId}<BR>";
                    createModelFile($filedsData['table'], $filedsData['table'], $filedsData['primaryKey'], $filedsData['db']);
               }
            }
             
        }
    }
    
    function listAction() { 
        $db = $_GET['db'];
        $table = $_GET['table']; 
        $tableObj = new $table;
        // print_r($tableObj);
        $filedObj = new filed();
        $list = $filedObj->getAll("`db` = '{$db}' and `table` = '{$table}' and `list` = '1'");
        $listStr = ''; 
        foreach($list as $value) {
            $listStr .=$value['enname'].',';
        }
        $listStr = trim($listStr, ',');
        $arr = $tableObj->limit(5)->where('1')->select(); 
        //print_r($arr);
        $viewObj = new View(false);
        if (!$viewObj->is_cached('list')) {
            $title = '模板';
            $viewObj->assign('title', $title)
                    ->assign('count', count($arr[0]))
                    ->assign('arr', $arr); 
        }
        $viewObj->display('list'); 
    }
    
    
    function editAction() {  
    
    }
    
    function deleteAction() {  
    
    }
    
    function addAction() {
        if (isset($_POST['submit'])) {
            $db = $_POST['qsf_db'];
            $table = $_POST['qsf_table'];
            unset($_POST['submit'], $_POST['qsf_db'], $_POST['qsf_table']); 
            $tableObj = new $table; 
            $tableObj->insert($_POST);
            header("location:http://localhost/qsf_mvc/index/index/index/");
        }else{
            $db = $_GET['db'];
            $table = $_GET['table']; 
            $tableObj = new $table;
            // print_r($tableObj);
            $filedObj = new filed();
            $add = $filedObj->getAll("`db` = '{$db}' and `table` = '{$table}'");
            /*
            $addArr = array(); 
            foreach($list as $value) {
                $value['add'] == 1 && $addArr[] = $value['enname'];
            }
            print_r($addArr);
             */
            //print_r($list); 
            $viewObj = new View(false);
            if (!$viewObj->is_cached('add')) {
                $title = '模板';
                $viewObj->assign('title', $title)
                        ->assign('db', $db)    
                        ->assign('table', $table)                                             
                        ->assign('add', $add); 
            }
            $viewObj->display('add');          
        }

    }


	function testAction() {
        exit('111');
		global $_SGLOBAL;
        if (submitcheck('testsubmit')) {
		   //print_r($GLOBALS);
		   print_r($_SGLOBAL);
		   echo '<hr>';
		   print_r(stripslashes_deep($_POST));
           exit('test');
        }else{
			_setCookie('test', '061007113', 10);
			_setCookie('hello', 'qishengfu', 10);
			echo _getCookie('test');
			echo '<hr>';
			echo _getCookie('hello',0);
			echo '<hr>';
			echo _getCookie('hello',1);
			echo '<hr>';
			print_r($_COOKIE);
		    $viewObj = new View(false);
            if (!$viewObj->is_cached('testsubmit')) {
                $title = '开始';
                $viewObj->assign('title', $title);
				$viewObj->assign('formhash', formhash());
            }
            $viewObj->display('testsubmit');
        }

    }

	function uploadAction() {
		print_r($_FILES);
		exit('');

    }

	function tAction() {
		print_r($_POST);
		print_r($_GET);
		print_r($_COOKIE);
    }
}